$(document).ready(function() {
    // 初始化页面加载时显示所有订单
	let targetUserId = $(".userid").val();
    allOrders();
    
    // 点击订单状态标签时筛选订单
    $('.order-tab').click(function() {
        // 移除所有标签的active类
        $('.order-tab').removeClass('active');
        // 为当前点击的标签添加active类
        $(this).addClass('active');
        
        // 获取当前状态文本
        let status = $(this).text().trim();
        
        if(status.includes("全部订单")){
            allOrders();
        }else if(status.includes("待付款")){
            filterOrdersByStatus(4); // 4代表待付款状态
        }else if(status.includes("待发货")){
            filterOrdersByStatus(2); // 2代表待发货状态
        }else if(status.includes("已完成")){
            filterOrdersByStatus(1); // 1代表已完成状态
        }else if(status.includes("已取消")){
            filterOrdersByStatus(3); // 3代表已取消状态
        }else if(status.includes("待收货")){
            filterOrdersByStatus(5); // 3代表待收货状态
        }
    });
    
    // 所有订单加载函数
    function allOrders() {
//    	console.log(targetUserId);
        let orderlist = $(".order-list");
        orderlist.empty();
        let num = 1;
        let shippingFee = 10;
        
        $.ajax({
            url:"/poj-java/selectAllOrders",
            type:"GET",
            data:{
                target_user_id :targetUserId
            },
            success:function(data){
                let listGoods = data.data.data[0].listGoods;
                let listOrders = data.data.data[0].listOrders;
                
                // 先计算并显示各状态订单数量
                calculateOrderStatusCounts(listOrders);
                
                // 渲染所有订单
                renderOrders(listGoods, listOrders, num, shippingFee);
            }
        });
    }
    
    // 根据状态筛选订单
    function filterOrdersByStatus(statusId) {
//    	let targetUserId = $(".userid").val();
        let orderlist = $(".order-list");
        orderlist.empty();
        let num = 1;
        let shippingFee = 10;
        
        $.ajax({
            url:"/poj-java/selectAllOrders",
            type:"GET",
            data:{
                target_user_id :targetUserId
            },
            success:function(data){
                let listGoods = data.data.data[0].listGoods;
                let listOrders = data.data.data[0].listOrders;
                
                // 筛选特定状态的订单
                let filteredOrders = [];
                let filteredGoods = [];
                
                for (var i = 0; i < listOrders.length; i++) {
                    if (listOrders[i].state == statusId) {
                        filteredOrders.push(listOrders[i]);
                        filteredGoods.push(listGoods[i]);
                    }
                }
                
                // 渲染筛选后的订单
                renderOrders(filteredGoods, filteredOrders, num, shippingFee);
            }
        });
    }
    
    // 渲染订单列表
    function renderOrders(listGoods, listOrders, num, shippingFee) {
        let orderlist = $(".order-list");
        orderlist.empty();
        
        if (listOrders.length === 0) {
            orderlist.html("<div class='no-orders'><i class='fas fa-box-open'><i>暂无相关订单</div>");
            return;
        }
        
        for (var i = 0; i < listGoods.length; i++) {
            let k = 0;
            let goods = listGoods[i][k];
            let order = listOrders[i];
            
            // 确定订单状态的显示文本和样式
            let statusText = '';
            let statusClass = '';
            
            switch(order.state) {
                case 1:
                    statusText = '已完成';
                    statusClass = 'status-completed';
                    break;
                case 2:
                    statusText = '待发货';
                    statusClass = 'status-shipping';
                    break;
                case 3:
                    statusText = '已取消';
                    statusClass = 'status-cancelled';
                    break;
                case 4:
                    statusText = '待付款';
                    statusClass = 'status-pending';
                    break;
                case 5:
                    statusText = '待收货';
                    statusClass = 'status-receiving';
                    break;
            }
            
            // 构建订单卡片HTML
            console.log(order)
            let orderCard = `<div class="order-card">
                <div class="order-card-header">
                    <div class="order-info">
                    	<input type="hidden" value=${order.ordersId} class="orderId">
                        <div class="order-id">订单号: ${order.orderNo}</div>
                        <div class="order-date">${order.datatime}</div>
                    </div>
                    <div class="order-status ${statusClass}">${statusText}</div>
                </div>
                
                <div class="order-card-body">
                    <div class="order-item">
                        <img src=${goods.goodimg} alt="商品图片" class="item-image">
                        <div class="item-details">
                            <div class="item-title">${goods.gooddec}</div>
                            <div class="item-price">${goods.goodprice}</div>
                            <div class="item-quantity">数量: <span class="quantity">${num}</span></div>
                        </div>
                    </div>
                    
                    <div class="order-summary">
                        <div class="summary-label">商品合计</div>
                        <div class="summary-value">¥<span class="valueMoney">${goods.goodprice*num}</span></div>
                    </div>
                    <div class="order-summary">
                        <div class="summary-label">运费</div>
                        <div class="summary-value">¥${shippingFee}</div>
                    </div>
                    <div class="order-summary total-amount">
                        <div class="summary-label">订单总额</div>
                        <div class="summary-value">¥${parseFloat(goods.goodprice)*num+parseFloat(shippingFee)}</div>
                    </div>
                </div>
                
                <div class="order-card-footer">
                    ${order.state == 1 ? 
                        '<button class="btn btn-outline-secondary order-action">查看物流</button>' +
                        '<button class="btn btn-gold order-action">再次购买</button>' +
                        '<button class="btn btn-outline-gold order-action">评价商品</button>' : 
                        
                        order.state == 2 ? 
                            '<button class="btn btn-outline-secondary order-action">联系卖家</button>'+
                            '<button class="btn btn-outline-gold order-action">提醒发货</button>': 
                        
                        order.state == 3 ?
                            '<button class="btn btn-outline-gold order-action">重新购买</button>' +
                            '<button class="btn btn-outline-secondary order-action deleteBtn" onclick="deleteOrders()">删除订单</button>':
                            
                        order.state == 4 ?
                            '<button class="btn btn-outline-secondary order-action deleteBtn" onclick="cancelOrders()">取消订单</button>' +
                            '<button class="btn btn-gold order-action buyNow" onclick="buyNow()">立即支付</button>' 	:
                            
                            '<button class="btn btn-outline-gold order-action" onclick="confirmReceipt()">待确认收货</button>'
                    }
                </div>
            </div>`;
            
            orderlist.append(orderCard);
            k++;
        }
    }
    
    // 计算并显示各状态订单数量
    function calculateOrderStatusCounts(listOrders) {
        let completedNum = 0; // 已完成订单数
        let unShippedNum = 0; // 待发货订单数目
        let cancelNum = 0;    // 已取消订单数目
        let obligationNum = 0;// 待付款订单数目
        let completeNum = 0;
        for (var i = 0; i < listOrders.length; i++) {
            let state = listOrders[i].state;
            if(state == 1){ // 已完成订单
                completedNum++;
            }else if(state == 2){ // 待发货订单
                unShippedNum++;
            }else if(state == 3){ // 已取消订单
                cancelNum++;
            }else if(state == 4){ // 待付款订单
                obligationNum++;
            }else if(state == 5){ //待收货
            	completeNum++;
            }
        }
        
        // 在标签上显示各状态订单数量
        if(completedNum != 0){
            let spanStr1 = `<span class="badge">${completedNum}</span>`;
            $('.order-tab:eq(3)').append(spanStr1);
        }
        if(unShippedNum != 0){
            let spanStr2 = `<span class="badge">${unShippedNum}</span>`;
            $('.order-tab:eq(2)').append(spanStr2);
        }
        if(cancelNum != 0){
            let spanStr3 = `<span class="badge">${cancelNum}</span>`;
            $('.order-tab:eq(4)').append(spanStr3);
        }
        if(obligationNum != 0){ 
            let spanStr4 = `<span class="badge">${obligationNum}</span>`;
            $('.order-tab:eq(1)').append(spanStr4); 
        }
        if(completeNum != 0){ 
            let spanStr5 = `<span class="badge">${completeNum}</span>`;
            $('.order-tab:eq(5)').append(spanStr5); 
        }
    }
});
function deleteOrders(){
	let orderId = $(".orderId").val();
	console.log(orderId);
	$.ajax({
		url:"/poj-java/deleteOrder",
		type:"GET",
		data:{
			orderId:orderId
		},
		success:function(data){
			console.log(data);
			if(data.code==200){
				alert("删除成功");
			}else{
				alert("删除失败");
			}
			location.reload();
		}
	})
};
function buyNow(){
	let orderId = $(".orderId").val();
	console.log(orderId);
	$.ajax({
		url:"/poj-java/sendGoods",
		type:"GET",
		data:{
			orderId:orderId,
			state:2
		},
		success:function(data){
			console.log(data);
			alert("支付成功");
			location.reload();
		}
	})
	
}
function cancelOrders(){
	let orderId = $(".orderId").val();
	console.log(orderId);
	$.ajax({
		url:"/poj-java/updateOrder",
		type:"GET",
		data:{
			orderId:orderId,
			state:3
		},
		success:function(data){
			console.log(data);
			if(data.code==200){
				alert("取消成功");
			}else{
				alert("取消失败");
			}
			location.reload();
		}
	})
	
}
function confirmReceipt(){
	let orderId = $(".orderId").val();
	console.log(orderId);
	$.ajax({
		url:"/poj-java/updateOrder",
		type:"GET",
		data:{
			orderId:orderId,
			state:1
		},
		success:function(data){
			console.log(data);
			if(data.code==200){
				alert("确认收货成功");
			}else{
				alert("确认收货失败");
			}
			location.reload();
		}
	})
}
